<template>
  <view class="container">
		<nav-ber :title="'我的协议'" :bgColor="'#f7f8ff'"></nav-ber>
		<view style="font-weight: 900;text-align: center;margin: 20rpx 0;font-size: 38rpx;">
			{{ listAgree[type] && listAgree[type].name }}
		</view>
		<view class="province">
			<view style="color: gray;font-size: 30rpx;" v-html="content">
			</view>
			
			<view class="sin_flex" style="margin: 40rpx 0;">
				<view style="display: flex;">甲方签字：</view>
				<view style="width: 300rpx;">签字时间：</view>
			</view>
			<view class="sin_flex">
				<view style="display: flex;">乙方签字：
				<view class="" style="position: relative;"  v-if="urlImg">
					<u--image :showLoading="true" :src="urlImg" width="80px" height="80px" @click="clickImgFun"></u--image>
					<view style="position: absolute;top: -10rpx;right: -10rpx;">
						<u-icon @click="delFun"  name="close-circle-fill" color="#2979ff" size="28"></u-icon>
					</view>
				</view>
				<span v-if="!urlImg" style="color:#2979ff" @click="signFun">请签字</span> </view>
				<view style="width: 300rpx;">签字时间：</view>
			</view>
		</view>
		<view class="bottom_w">
			<u-button @click="addFun" type="primary" :text="type == 2? '提交' : '下一步'"></u-button>
		</view>
		<u-modal v-if="showTimefilter" :show="showTimefilter" @confirm="confirmFunXz"  content='您已经提交了协议;协议审核通过后即可激活成功,请耐心等待'></u-modal>
  </view>
</template>
<script>
	import { listByMr, addAgreement } from '@/api/personalCenter.js'
	import Config from '@/core/config'
	const apiUrl = Config.get('apiUrl')
	
  export default {
    data() {
			return {
				showTimefilter: false,
				fal: false,
				listAgree: [],
				urlImg: '',
				// urlImg: 'https://cdn.uviewui.com/uview/album/1.jpg',
				keyword: '',
				ispro: '1',
				bottonisShow: true,
				type: 0,
				datas: [],
				content: '',
				name: '',
				id: '',
			}
    },
		onLoad: function (option) { //option为object类型，会序列化上个页面传递的参数
			this.id = option.id
			this.listByMrFun()
			if (uni.getStorageSync('singImg')) {
				this.datas  = JSON.parse(uni.getStorageSync('singImg'))
			}
		},
		onShow() {
			if (uni.getStorageSync('singImg')) {
				if(this.fal){
					this.fal = false
					return
				}
				uni.showLoading({
				  title: '加载中',
				  mask: true,
					duration: 2500
				})
				this.datas  = JSON.parse(uni.getStorageSync('singImg'))
				this.urlImg = this.datas[this.type]?.url
				if (this.urlImg) {
					let _this = this
					uni.uploadFile({
						url: apiUrl + '/file/upload',
						filePath: _this.datas[_this.type]?.url,
						name: "file",
						header: {
							'token': uni.getStorageSync('token')
						},
						success: (val) => {
							
							let res = JSON.parse(val.data)
							_this.urlImg = res.data.url
							let arr;
							if (uni.getStorageSync('singImg')) {
								arr = JSON.parse(uni.getStorageSync('singImg'))
							} else {
								arr = []
							}
							arr[_this.type] = {
								type: _this.type == 0? 0 : (_this.type == 1? 2 : 3),
								url: res.data.url
							}
							uni.setStorage({
								key: 'singImg',
								data: JSON.stringify(arr)
							})
							setTimeout(() => {
								uni.hideLoading()
							}, 500)
						},
					});
				}
				// for(let i = 0; i<this.datas.length; i++) {
				// 	if (!this.datas[i].url) {
				// 		this.type = i
				// 		break
				// 	}
				// }
			}
			// let imgs = JSON.parse(uni.getStorageSync('singImg'))
			// if (imgs) {
			// 	this.urlImg = imgs[this.type].url
			// }
			
			// uni.setStorage({
			// 	key: 'userInfoRole',
			// 	data: JSON.stringify(resmin.data)
			// })
			// uni.removeStorageSync("token");
			// JSON.parse(uni.getStorageSync('userInfo')).userType == '02'
		},
		methods: {
			base64ToFile(data) {
			  const dataArr = data.split(",");
			  const byteString = atob(dataArr[1]);
			  const options = {
			      type: "image/jpeg",
			      endings: "native"
			  };
			  const u8Arr = new Uint8Array(byteString.length);
			  for (let i = 0; i < byteString.length; i++) {
			      u8Arr[i] = byteString.charCodeAt(i);
			  }
			  let fileOfBlob = new File([u8Arr], new Date().getTime() + ".jpg", options);//返回文件流
			  return fileOfBlob
			},
			parseBlob(base64) {
				
				var arr = base64.split(',');
				
				var mime = arr[0].match(/:(.*?);/)[1];
				
				var bstr = atob(arr[1]);
				
				var n = bstr.length;
				
				var u8arr = new Uint8Array(n);
				
				for(var i = 0; i < n; i++) {
				
				u8arr[i] = bstr.charCodeAt(i);
				
				}
				
				var url = URL || webkitURL;
				
				return url.createObjectURL(new Blob([u8arr], {type: mime}));
			
			},
			confirmFunXz() {
				this.showTimefilter = false
				uni.navigateBack({
					delta: 1,
				})
			},
			addFun() {
				if (uni.getStorageSync('singImg')) {
					this.datas  = JSON.parse(uni.getStorageSync('singImg'))
					if (!this.datas[this.type]?.url) {
						uni.showToast({
						  title: '请先签字',
						  icon: "none",
						  duration: 2000,
						})
						return
					}
				} else {
					uni.showToast({
					  title: '请先签字',
					  icon: "none",
					  duration: 2000,
					})
					return
				}
				if (this.type == 2) {
					let agreementList = []
					this.listAgree.forEach((item, index) => {
						agreementList.push({
							agreementId: item.id,
							agreementName: item.name,
							mrSignedUrl: this.datas[index].url
						})
					})
					addAgreement({
						agreementList,
						id: this.id,
						load: false
					}).then((res) => {
						this.showTimefilter = true
						
					})
				} else {
					
					this.type++
					this.content = this.listAgree[this.type].content
					this.urlImg = this.datas[this.type]?.url??''
				}
				
			},
			listByMrFun() {
				listByMr(false).then((res) => {
					this.listAgree = res.rows
					this.content = res.rows[0].content
				})
			},
			delFun() {
				this.urlImg = ''
			},
			clickImgFun() {
				this.fal = true
				uni.previewImage({
						current: 0,
						urls: [this.urlImg],
				})
			},
			formatDate(date,formatStr) {
				let arrWeek = ['日', '一', '二', '三', '四', '五', '六'],
					str = formatStr.replace(/yyyy|YYYY/, date.getFullYear()).replace(/yy|YY/, this.$addZero(date.getFullYear() % 100,
						2)).replace(/mm|MM/, this.$addZero(date.getMonth() + 1, 2)).replace(/m|M/g, date.getMonth() + 1).replace(
						/dd|DD/, this.$addZero(date.getDate(), 2)).replace(/d|D/g, date.getDate()).replace(/hh|HH/, this.$addZero(date
						.getHours(), 2)).replace(/h|H/g, date.getHours()).replace(/ii|II/, this.$addZero(date.getMinutes(), 2))
					.replace(/i|I/g, date.getMinutes()).replace(/ss|SS/, this.$addZero(date.getSeconds(), 2)).replace(/s|S/g, date
						.getSeconds()).replace(/w/g, date.getDay()).replace(/W/g, arrWeek[date.getDay()]);
				return str
			 
			},
			$addZero(v, size) {
				for (var i = 0, len = size - (v + "").length; i < len; i++) {
					v = "0" + v
				}
				return v + ""
			},
			signFun() {
				uni.navigateTo({
					url: "/pages/personalCenter/sign/index?type=" + this.type
				})
			},
		}
  }
</script>
<style lang="scss" scoped>
	.container {
		background-color: #f7f8ff;
		display: flex;
		flex-direction: column;
		height: 100vh;
		overflow: hidden;
	}
	.province {
		flex: 1;
		overflow: scroll;
		padding: 0 20rpx;
		margin-top: 20rpx;
	}
	.bottom_w {
		margin: 20rpx 50rpx;
		border-radius: 10rpx;
		overflow: hidden;
	}
	.sin_flex {
		display: flex;
		justify-content: space-between;
		margin: 20rpx 0;
	}
</style>
